'use client';

import { useState } from 'react';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { mockOrders, mockUnboxResults, categories, products } from '@/lib/mockData';

export default function ProfilePage() {
  const { state, dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [activeTab, setActiveTab] = useState('boxes');

  if (!state.isLoggedIn) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-8xl mb-6">👤</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-4">请先登录</h2>
          <p className="text-gray-600 mb-8">登录后查看您的订单和开箱记录</p>
          <button className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
            立即登录
          </button>
        </div>
      </div>
    );
  }

  const user = state.user!;

  const getMemberLevelInfo = (level: string) => {
    const levels = {
      bronze: { name: '青铜会员', color: 'text-orange-600', bgColor: 'bg-orange-100' },
      silver: { name: '白银会员', color: 'text-gray-600', bgColor: 'bg-gray-100' },
      gold: { name: '黄金会员', color: 'text-yellow-600', bgColor: 'bg-yellow-100' },
      diamond: { name: '钻石会员', color: 'text-purple-600', bgColor: 'bg-purple-100' }
    };
    return levels[level as keyof typeof levels] || levels.bronze;
  };

  const memberInfo = getMemberLevelInfo(user.memberLevel);

  const getStatusInfo = (status: string) => {
    const statusMap = {
      pending: { name: '待支付', color: 'text-orange-600', bgColor: 'bg-orange-100' },
      paid: { name: '已支付', color: 'text-blue-600', bgColor: 'bg-blue-100' },
      shipped: { name: '已发货', color: 'text-purple-600', bgColor: 'bg-purple-100' },
      delivered: { name: '已送达', color: 'text-green-600', bgColor: 'bg-green-100' },
      completed: { name: '已完成', color: 'text-gray-600', bgColor: 'bg-gray-100' }
    };
    return statusMap[status as keyof typeof statusMap] || statusMap.pending;
  };

  // 跳转到开箱页面
  const handleUnbox = (boxId: string) => {
    window.location.href = `/unbox/${boxId}`;
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* 用户信息卡片 */}
        <div className="bg-gradient-to-r from-yellow-400 to-orange-400 rounded-lg p-6 mb-8 text-black">
          <div className="flex items-center space-x-4">
            <div className="w-20 h-20 bg-white rounded-full flex items-center justify-center text-2xl">
              👤
            </div>
            <div className="flex-1">
              <h1 className="text-2xl font-bold mb-2">{user.name}</h1>
              <div className="flex items-center space-x-4 text-sm">
                <span>{user.phone}</span>
                <span className={`px-2 py-1 rounded ${memberInfo.bgColor} ${memberInfo.color} font-medium`}>
                  {memberInfo.name}
                </span>
              </div>
            </div>
            <div className="text-right">
              <div className="text-sm opacity-80">账户余额</div>
              <div className="text-2xl font-bold">¥{user.balance}</div>
              <div className="text-sm opacity-80">积分: {user.points}</div>
            </div>
          </div>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-2 md:grid-cols-6 gap-4 mb-8">
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-gray-800">{state.purchasedBoxes.length}</div>
            <div className="text-sm text-gray-600">购买盲盒</div>
          </div>
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-green-600">{state.purchasedBoxes.filter(b => b.isUnboxed).length}</div>
            <div className="text-sm text-gray-600">已开箱</div>
          </div>
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-orange-600">{state.purchasedBoxes.filter(b => !b.isUnboxed).length}</div>
            <div className="text-sm text-gray-600">待开箱</div>
          </div>
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-purple-600">
              ¥{state.purchasedBoxes.filter(b => b.isUnboxed).reduce((sum, box) => sum + (box.unboxResult?.actualValue || 0), 0)}
            </div>
            <div className="text-sm text-gray-600">开箱价值</div>
          </div>
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-pink-600">{state.lotteryResults.length}</div>
            <div className="text-sm text-gray-600">抽奖次数</div>
          </div>
          <div className="bg-white rounded-lg p-4 text-center shadow-sm">
            <div className="text-2xl font-bold text-indigo-600">{state.signInRecord?.consecutiveDays || 0}</div>
            <div className="text-sm text-gray-600">连续签到</div>
          </div>
        </div>

        {/* 标签页 */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="border-b border-gray-200">
            <nav className="flex">
              {[
                { id: 'boxes', name: '我的盲盒', icon: '📦' },
                { id: 'unbox', name: '开箱记录', icon: '🎁' },
                { id: 'orders', name: '我的订单', icon: '🛍️' },
                { id: 'lottery', name: '抽奖记录', icon: '🎰' },
                { id: 'profile', name: '个人资料', icon: '👤' }
              ].map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex-1 py-4 px-6 text-center border-b-2 transition-colors ${
                    activeTab === tab.id
                      ? 'border-orange-500 text-orange-600 bg-orange-50'
                      : 'border-transparent text-gray-600 hover:text-gray-800'
                  }`}
                >
                  <span className="mr-2">{tab.icon}</span>
                  {tab.name}
                </button>
              ))}
            </nav>
          </div>

          <div className="p-6">
            {/* 我的盲盒标签页 */}
            {activeTab === 'boxes' && (
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-4">我的盲盒收藏</h3>
                {state.purchasedBoxes.length > 0 ? (
                  <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {state.purchasedBoxes.map((box) => {
                      const category = categories.find(c => c.id === box.productCategory);
                      const product = products.find(p => p.id === box.productId);
                      return (
                        <div key={box.id} className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                          <div className={`h-32 bg-gradient-to-br ${product?.bgColor || 'from-gray-400 to-gray-600'} rounded-lg flex items-center justify-center mb-4`}>
                            <span className="text-3xl">{category?.icon || '📦'}</span>
                          </div>
                          <h4 className="font-semibold text-gray-800 mb-2">{box.productName}</h4>
                          <div className="text-sm text-gray-600 mb-3">
                            <div>购买价格: ¥{box.price}</div>
                            <div>购买时间: {new Date(box.purchaseDate).toLocaleDateString()}</div>
                          </div>
                          
                          {box.isUnboxed ? (
                            <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                              <div className="flex items-center justify-between mb-2">
                                <span className="text-green-600 font-semibold">已开箱</span>
                                <span className={`px-2 py-1 rounded text-xs ${
                                  box.unboxResult?.rarity === 'legendary' ? 'bg-yellow-100 text-yellow-800' :
                                  box.unboxResult?.rarity === 'epic' ? 'bg-purple-100 text-purple-800' :
                                  box.unboxResult?.rarity === 'rare' ? 'bg-blue-100 text-blue-800' :
                                  'bg-gray-100 text-gray-800'
                                }`}>
                                  {box.unboxResult?.rarity}
                                </span>
                              </div>
                              <div className="text-sm">
                                <div className="font-medium">{box.unboxResult?.actualItem}</div>
                                <div className="text-gray-600">{box.unboxResult?.description}</div>
                                <div className="text-green-600 font-semibold">价值: ¥{box.unboxResult?.actualValue}</div>
                              </div>
                            </div>
                          ) : (
                            <button
                              onClick={() => handleUnbox(box.id)}
                              className="w-full py-2 px-4 rounded-lg font-medium transition-all bg-gradient-to-r from-yellow-400 to-orange-400 text-black hover:shadow-lg"
                            >
                              📦 立即开箱
                            </button>
                          )}
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <div className="text-center py-16">
                    <div className="text-6xl mb-4">📦</div>
                    <h4 className="text-xl font-semibold text-gray-800 mb-2">暂无盲盒</h4>
                    <p className="text-gray-600 mb-6">快去购买你的第一个盲盒吧！</p>
                    <a href="/" className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
                      🛍️ 去购买盲盒
                    </a>
                  </div>
                )}
              </div>
            )}

            {/* 开箱记录标签页 */}
            {activeTab === 'unbox' && (
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-4">开箱记录</h3>
                {state.purchasedBoxes.filter(b => b.isUnboxed).length > 0 ? (
                  <div className="space-y-4">
                    {state.purchasedBoxes.filter(b => b.isUnboxed).map((box) => (
                      <div key={box.id} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex justify-between items-start mb-3">
                          <div>
                            <h4 className="font-semibold text-gray-800">{box.productName}</h4>
                            <p className="text-sm text-gray-600">开箱时间: {new Date(box.unboxResult?.unboxDate || '').toLocaleString()}</p>
                          </div>
                          <span className={`px-2 py-1 rounded text-xs ${
                            box.unboxResult?.rarity === 'legendary' ? 'bg-yellow-100 text-yellow-800' :
                            box.unboxResult?.rarity === 'epic' ? 'bg-purple-100 text-purple-800' :
                            box.unboxResult?.rarity === 'rare' ? 'bg-blue-100 text-blue-800' :
                            'bg-gray-100 text-gray-800'
                          }`}>
                            {box.unboxResult?.rarity}
                          </span>
                        </div>
                        <div className="grid md:grid-cols-3 gap-4">
                          <div>
                            <span className="text-sm text-gray-600">获得物品</span>
                            <p className="font-medium">{box.unboxResult?.actualItem}</p>
                          </div>
                          <div>
                            <span className="text-sm text-gray-600">实际价值</span>
                            <p className="font-medium text-green-600">¥{box.unboxResult?.actualValue}</p>
                          </div>
                          <div>
                            <span className="text-sm text-gray-600">满意度</span>
                            <p className="font-medium">{'⭐'.repeat(box.unboxResult?.satisfaction || 0)}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-16">
                    <div className="text-6xl mb-4">🎁</div>
                    <h4 className="text-xl font-semibold text-gray-800 mb-2">暂无开箱记录</h4>
                    <p className="text-gray-600">购买盲盒后可以在这里查看开箱记录</p>
                  </div>
                )}
              </div>
            )}

            {/* 订单记录标签页 */}
            {activeTab === 'orders' && (
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-4">我的订单</h3>
                <div className="space-y-4">
                  {mockOrders.map((order) => {
                    const statusInfo = getStatusInfo(order.status);
                    return (
                      <div key={order.id} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex justify-between items-start mb-3">
                          <div>
                            <h4 className="font-semibold text-gray-800">订单号: {order.id}</h4>
                            <p className="text-sm text-gray-600">下单时间: {order.createdAt}</p>
                          </div>
                          <span className={`px-3 py-1 rounded-full text-sm ${statusInfo.bgColor} ${statusInfo.color}`}>
                            {statusInfo.name}
                          </span>
                        </div>
                        <div className="space-y-2">
                          {order.items.map((item, index) => (
                            <div key={index} className="flex justify-between items-center">
                              <span>{item.product.name} x {item.quantity}</span>
                              <span className="font-medium">¥{(item.product.price * item.quantity).toFixed(2)}</span>
                            </div>
                          ))}
                        </div>
                        <div className="border-t pt-3 mt-3 flex justify-between items-center">
                          <span className="text-lg font-bold">总计: ¥{order.total}</span>
                          {order.trackingNumber && (
                            <span className="text-sm text-gray-600">物流单号: {order.trackingNumber}</span>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* 抽奖记录标签页 */}
            {activeTab === 'lottery' && (
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-4">抽奖记录</h3>
                {state.lotteryResults.length > 0 ? (
                  <div className="space-y-4">
                    {state.lotteryResults.map((result) => (
                      <div key={result.id} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex justify-between items-center">
                          <div>
                            <h4 className="font-semibold text-gray-800">{result.prizeName}</h4>
                            <p className="text-sm text-gray-600">抽奖时间: {new Date(result.createdAt).toLocaleString()}</p>
                          </div>
                          <div className="text-right">
                            <div className="font-medium text-purple-600">
                              {result.prizeType === 'points' ? `${result.prizeValue}积分` : `价值¥${result.prizeValue}`}
                            </div>
                            <span className={`inline-block px-2 py-1 rounded text-xs mt-1 ${
                              result.claimed ? 'bg-green-100 text-green-800' : 'bg-orange-100 text-orange-800'
                            }`}>
                              {result.claimed ? '已领取' : '待领取'}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-16">
                    <div className="text-6xl mb-4">🎰</div>
                    <h4 className="text-xl font-semibold text-gray-800 mb-2">暂无抽奖记录</h4>
                    <p className="text-gray-600">通过每日签到获得抽奖机会</p>
                  </div>
                )}
              </div>
            )}

            {/* 个人资料标签页 */}
            {activeTab === 'profile' && (
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-6">个人资料</h3>
                <div className="max-w-md space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" value={user.name} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" readOnly />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">手机号</label>
                    <input type="text" value={user.phone} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" readOnly />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <input type="email" value={user.email} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" readOnly />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">会员等级</label>
                    <div className={`inline-block px-3 py-2 rounded-lg ${memberInfo.bgColor} ${memberInfo.color} font-medium`}>
                      {memberInfo.name}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}